package com.koron.css2.serviceManage.utils;

import com.google.common.collect.Lists;
import com.koron.css2.serviceManage.bean.LogOperateBean;
import com.koron.css2.serviceManage.bean.SelectDictionaryListBean;
import com.koron.css2.serviceManage.mapper.LogOperateMapper;
import com.koron.css2.serviceManage.mapper.SelectDictionaryListMapper;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author DaiSy
 */
public class CommonUtils {

    private static final long DAY_MINUTES = 24 * 60 * 60 * 1000;

    /**
     * 获取当月第几天
     *
     * @return
     */
    public static int getCurrentMonthToDay() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        return Integer.parseInt(sdf.format(cal.getTime()));
    }

    /**
     * 根据名称从数据字典获取值
     *
     * @param factory
     * @param name
     * @return
     */
    public static String getDicValueByName(SessionFactory factory, String name) {
        SelectDictionaryListMapper mapper = factory.getMapper(SelectDictionaryListMapper.class);
        SelectDictionaryListBean dicValueByName = mapper.getDicValueByName(name);
        if (dicValueByName != null) {
            return dicValueByName.getValue();
        } else {
            return null;
        }
    }

    /**
     * 产生N位非固定长度随机数(0-9999)     
     *
     * @return int
     */
    public static Integer getFourRandom(int lenght) {
        Random random = new Random();
        String fourRandom = "1";
        for (int i = 1; i <= lenght; i++)
            fourRandom = fourRandom + "0";
        fourRandom = random.nextInt(Integer.parseInt(fourRandom)) + "";
        int randLength = fourRandom.length();
        if (randLength < lenght) {
            for (int i = 1; i <= lenght - randLength; i++)
                fourRandom = "0" + fourRandom;
        }
        return Integer.parseInt(fourRandom);
    }

    /**
     * 添加登录日志
     *
     * @param factory
     * @param staff       用户
     * @param type        日志类型 1:登陆 2：操作 3：运行
     * @param description 描述
     * @param module      模块
     */
    public static void addLog(SessionFactory factory, String staff, int type, String description, String module) {
        LogOperateMapper mapper = factory.getMapper(LogOperateMapper.class);
        LogOperateBean logOperateBean = new LogOperateBean();
        logOperateBean.setId(new ObjectId().toHexString());
        logOperateBean.setType(type);
        logOperateBean.setTime(CommonUtils.getCurrentTime());
        logOperateBean.setDescription(description);
        logOperateBean.setStaff(staff);
        logOperateBean.setModule(module);
        mapper.addLogOperate(logOperateBean);
    }

    /**
     * 获取当前时间（24 yyyy-MM-dd HH:mm:ss）
     *
     * @return
     */
    public static String getCurrentTime() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(cal.getTime());
    }

    /**
     * 将时间戳按照指定格式转换为日期
     *
     * @param seconds
     * @param format
     * @return
     */
    public static String timeStampToDate(long seconds, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String date = null;
        date = sdf.format(new Date(Long.valueOf(seconds)));
        return date;
    }

    /**
     * 获取当前时间的时间戳
     *
     * @return
     */
    public static Date getNowTime() {
        Calendar cal = Calendar.getInstance();
        DateFormat dateFormatterChina = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);// 格式化输出
        TimeZone timeZoneChina = TimeZone.getTimeZone("Asia/Shanghai");// 获取时区
        dateFormatterChina.setTimeZone(timeZoneChina);// 设置系统时区

        return cal.getTime();
    }

    /**
     * 获取当前日期（yyyy-MM-dd）
     *
     * @return
     */
    public static String getCurrentDate() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 获取当前月份（yyyy-MM）
     *
     * @return
     */
    public static String getCurrentMonth() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(cal.getTime());
    }

    /**
     * 获取当前月份（yyyyMM）
     *
     * @return
     */
    public static String getYearMonth() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.format(cal.getTime());
    }

    /**
     * 获取当天在月份的第几天
     *
     * @return
     */
    public static int getCurrentDay() {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        return day;
    }

    public static int getDay(String date) throws ParseException {
        DateFormat dfdate = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = dfdate.parse(date);
        Calendar g = Calendar.getInstance();
        g.setTime(d1);
        int day = g.get(Calendar.DATE);
        return day;
    }

    /**
     * 获取当前日期前n天(yyyy-MM-dd)
     *
     * @return
     */
    public static String getBeforeDate(long day) {
        // 将字符串转为日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        long currentTimeMillis = cal.getTime().getTime();
        // 前day天
        currentTimeMillis = currentTimeMillis - day * DAY_MINUTES;
        cal.setTimeInMillis(currentTimeMillis);
        return sdf.format(cal.getTime());
    }

    /**
     * 获取当前日期前n天(yyyyMMdd)
     *
     * @return
     */
    public static String getBeforeDateFormat(long day) {
        // 将字符串转为日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        long currentTimeMillis = cal.getTime().getTime();
        // 前day天
        currentTimeMillis = currentTimeMillis - day * DAY_MINUTES;
        cal.setTimeInMillis(currentTimeMillis);
        return sdf.format(cal.getTime());
    }

    /**
     * 获取当前时间（24 HH:mm:ss）
     *
     * @return
     */
    public static String getCurrentOnlyTime() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(cal.getTime());
    }

    /**
     * 验证IP是否属于某个IP段 ipSection IP段（以'-'分隔） ip 所验证的IP号码
     */
    public static boolean ipExistsInRange(String ip, String ipSection) {
        ipSection = ipSection.trim();
        ip = ip.trim();
        int idx = ipSection.indexOf('-');
        String beginIP = ipSection.substring(0, idx);
        String endIP = ipSection.substring(idx + 1);
        return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP);
    }

    public static long getIp2long(String ip) {
        ip = ip.trim();
        String[] ips = ip.split("\\.");
        long ip2long = 0L;
        for (int i = 0; i < 4; ++i) {
            ip2long = ip2long << 8 | Integer.parseInt(ips[i]);
        }
        return ip2long;
    }

    public static long getIp2long2(String ip) {
        ip = ip.trim();
        String[] ips = ip.split("\\.");
        long ip1 = Integer.parseInt(ips[0]);
        long ip2 = Integer.parseInt(ips[1]);
        long ip3 = Integer.parseInt(ips[2]);
        long ip4 = Integer.parseInt(ips[3]);
        long ip2long = 1L * ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4;
        return ip2long;
    }

    /**
     * match *.*.*.*
     *
     * @return
     */
    public static boolean isIpAddress(String ip) {
        String regularExpression = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
        Pattern pattern = Pattern.compile(regularExpression);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

    /**
     * ip地址段是否合法
     *
     * @param ipSegment
     * @return
     */
    public static boolean isIpAddressSegment(String ipSegment) {
        boolean ipCheck = true;
        String[] split = ipSegment.split(",");
        for (String string : split) {
            if (string.indexOf("-") != -1) {
                // 如果有“-”，再按照“-”拆分，一个个*.*.*.*的ip
                String[] split2 = string.split("-");
                if (split2.length == 2) {
                    if (!isIpAddress(split2[0]) || !isIpAddress(split2[1])) {
                        ipCheck = false;
                    }
                } else {
                    // 无效ip段
                    ipCheck = false;
                }
                if (ipCheck == false) {
                    return ipCheck;
                }
            } else if (string.indexOf("*") != -1) {
                // 如果有“*”，按照*号的规则匹配
                String split2 = string.replaceAll("\\*", "1");
                if (!isIpAddress(split2)) {
                    ipCheck = false;
                    return ipCheck;
                }
            } else {
                // 剩下的就是单个ip的
                if (!isIpAddress(string)) {
                    ipCheck = false;
                    return ipCheck;
                }
            }
        }
        return ipCheck;
    }

    /**
     * 验证ip是否在id地址段中 IP地址段规则：可用逗号（,）、横杆（-）、星号（*）等分隔符，
     * 如192.168.1.1-192.168.1.100,192.168.1.200,192.168.4.*
     *
     * @param ip        操作方ip（或者代理ip）
     * @param ipSegment ip地址段
     * @return
     */
    public static boolean ipIsInIpAddressSegment(String ip, String ipSegment) {
        boolean ipCheck = false;
        if (!isIpAddress(ip)) {
            return ipCheck;
        } else {
            // 先按照逗号拆分
            String[] split = ipSegment.split(",");
            for (String string : split) {
                if (string.indexOf("-") != -1) {
                    // 如果有“-”，再按照“-”拆分，一个个*.*.*.*的ip
                    String[] split2 = string.split("-");
                    if (split2.length == 2) {
                        if (isIpAddress(split2[0]) && isIpAddress(split2[1])) {
                            ipCheck = ipExistsInRange(ip, split2[0] + "-" + split2[1]);
                        } else {
                            // 无效ip段
                            ipCheck = false;
                        }
                    } else {
                        // 无效ip段
                        ipCheck = false;
                    }
                    if (ipCheck == false) {
                        return ipCheck;
                    }
                } else if (string.indexOf("*") != -1) {
                    // 如果有“*”，按照*号的规则匹配
                    String[] split2 = string.split("\\*");
                    int length = split2.length;
                    String[] split3 = string.split("\\.");
                    if (split3.length != 4 && string.lastIndexOf("*") != string.length() - 1) {
                        ipCheck = false;
                    } else if (length == 1) {
                        ipCheck = ipExistsInRange(ip, split2[0] + "0" + "-" + split2[0] + "255");
                    } else if (length == 2) {
                        ipCheck = ipExistsInRange(ip, split2[0] + "0.0" + "-" + split2[0] + "255.255");
                    } else if (length == 3) {
                        ipCheck = ipExistsInRange(ip, split2[0] + "0.0.0" + "-" + split2[0] + "255.255.255");
                    } else if (length == 4) {
                        ipCheck = ipExistsInRange(ip, "0.0.0.0" + "-" + "255.255.255.255");
                    } else {
                        // 无效ip地址
                        ipCheck = false;
                    }
                    if (ipCheck == false) {
                        return ipCheck;
                    }
                } else {
                    // 剩下的就是单个ip的
                    if (isIpAddress(string)) {
                        ipCheck = ipExistsInRange(ip, string + "-" + string);
                    } else {
                        // 无效ip
                        ipCheck = false;
                    }
                    if (ipCheck == false) {
                        return ipCheck;
                    }
                }
            }
        }
        return ipCheck;
    }

    /**
     * 是否在限制时间前
     *
     * @param time      (HH:mm:ss) 当前时间
     * @param limitTime (HH:mm:ss) 计算好的限制时间
     * @return
     */
    public static boolean timeLimitRepase(String time, String limitTime) {
        try {
            String times[] = time.split(":");
            String limitTimes[] = limitTime.split(":");
            if (times.length == 3 && limitTimes.length == 3) {
                int current = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
                int limit = Integer.parseInt(limitTimes[0]) * 60 + Integer.parseInt(limitTimes[1]);
                if (limit - current >= 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * 获取字符串格式为"yyyy-MM-dd"的日期之间的天数
     *
     * @param bday
     * @param eday
     * @return
     */
    public static int getDayBetweenToDays(String bday, String eday) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date sdate = null;
        Date eDate = null;
        int betweendays = 0;
        try {
            sdate = df.parse(bday);
            eDate = df.parse(eday);
            betweendays = (int) ((eDate.getTime() - sdate.getTime()) / (1000 * 60 * 60 * 24) + 0.5);// 天数间隔
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            df = new SimpleDateFormat("yyyyMM-dd");
            try {
                sdate = df.parse(bday);
                eDate = df.parse(eday);
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
            betweendays = (int) ((eDate.getTime() - sdate.getTime()) / (1000 * 60 * 60 * 24) + 0.5);// 天数间隔
        }

        return betweendays + 1;
    }

    /**
     * 获取字符串格式为"yyyyMMdd"的日期之间的天数
     *
     * @param bday
     * @param eday
     * @return
     */
    public static int getDaysBetweenToDays(String bday, String eday) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        Date sdate = null;
        Date eDate = null;
        int betweendays = 0;
        try {
            sdate = df.parse(bday);
            eDate = df.parse(eday);
            betweendays = (int) ((eDate.getTime() - sdate.getTime()) / (1000 * 60 * 60 * 24) + 0.5);// 天数间隔
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            df = new SimpleDateFormat("yyyyMM-dd");
            try {
                sdate = df.parse(bday);
                eDate = df.parse(eday);
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
            betweendays = (int) ((eDate.getTime() - sdate.getTime()) / (1000 * 60 * 60 * 24) + 0.5);// 天数间隔
        }

        return betweendays + 1;
    }

    /**
     * 获取客户端IP
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;

    }

    // 获取某月有多少天
    public static int getDaysByMonth(int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    // 获取距本月前n月的月份
    public static String getMonthBefore(int months) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -months);
        String month = sd.format(cal.getTime());
        return month;
    }

    /**
     * 是否存在空值
     *
     * @param field
     * @return
     */
    public static boolean checkIsNull(Object... field) {
        for (Object str : field) {
            if (StringUtils.isBlank((String) str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取两个日期之间所有的日期（包括两个日期）
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getBetweenDates(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    /**
     * 比较两个时间戳相差的秒数
     *
     * @param before
     * @param after
     * @return
     */
    public static double compareTwoTimeStamp(Long before, Long after) {
        return (after - before) / 1000;
    }

    /**
     * 判断字符串是否全是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static String getMonthBeforeMonth(String month, int interval) {
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String months = "";
        try {
            Date d1 = df.parse(month);
            Calendar g = Calendar.getInstance();
            g.setTime(d1);
            g.add(Calendar.MONTH, -interval);
            months = df.format(g.getTime());
            return months;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return months;
    }

    public static String getMonthAfterMonth(String month, int interval) {
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String months = "";
        try {
            Date d1 = df.parse(month);
            Calendar g = Calendar.getInstance();
            g.setTime(d1);
            g.add(Calendar.MONTH, interval);
            months = df.format(g.getTime());
            return months;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return months;
    }

    public static String getMonthBeforeDays(String date, int days) {
        DateFormat df = new SimpleDateFormat("yyyyMM");
        DateFormat dfdate = new SimpleDateFormat("yyyy-MM-dd");
        String months = "";
        try {
            Date d1 = dfdate.parse(date);
            Calendar g = Calendar.getInstance();
            g.setTime(d1);
            g.add(Calendar.DATE, -days);
            months = df.format(g.getTime());
            return months;
        } catch (ParseException e) {
            throw new RuntimeException("获取月份失败", e);
        }
    }

    /**
     * 获取目标日期的去年的日期
     *
     * @param daytime
     * @return
     */
    public static String getLastYearDay(String daytime) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String lastYear = "";
        try {
            Date nowday = dateFormat.parse(daytime);
            Calendar temp = Calendar.getInstance();
            temp.setTime(nowday);
            temp.add(Calendar.YEAR, -1);
            Date y = temp.getTime();
            lastYear = dateFormat.format(y);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lastYear;

    }

    /**
     * 忽略字段
     *
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            if (pd.getName().equals("createInfo") || pd.getName().equals("updateInfo")) {
                continue;
            }
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * copy两个对象之间的属性值
     *
     * @param src    源
     * @param target 目标
     */
    public static void copyPropertiesIgnoreNull(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

    /**
     * 判断某个日期是否在两个日期范围之内
     *
     * @param before
     * @param after
     * @return
     * @throws ParseException
     */
    public static boolean checkToDayInBeforeAndAfter(String before, String after) throws ParseException {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sd.parse(before);
        Date date2 = sd.parse(after);
        Date date3 = sd.parse(CommonUtils.getCurrentDate());
        if (date1.getTime() <= date3.getTime() && date2.getTime() >= date3.getTime()) {
            return true;
        }
        return false;
    }

    /**
     * 转换日期字符串格式
     *
     * @param dateString
     * @return
     * @throws ParseException
     */
    public static String dateStringFormat(String dateString) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = df.parse(dateString);
        return df1.format(date);
    }

    /**
     * 判断字符串中是否包含中文
     *
     * @param str 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     *
     * @param code
     * @return
     */
    public static String autoGenericCode(String code, int num) {
        DecimalFormat df = new DecimalFormat(code);
        String numStr = df.format(num);
        return numStr;
    }

    /**
     * 获取距本月后n月的月份
     *
     * @param months
     * @return
     */
    public static String getMonthAfterYM(int months) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, months);
        String month = sd.format(cal.getTime());
        return month;
    }

    /**
     * 校验手机号
     *
     * @param str
     * @return
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        String s2 = "^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";// 验证手机号
        if (StringUtils.isNotBlank(str)) {
            p = Pattern.compile(s2);
            m = p.matcher(str);
            b = m.matches();
        }
        return b;
    }

    public static BigDecimal add(double v1, double... v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        for (double value : v2) {
            BigDecimal b2 = new BigDecimal(Double.toString(value));
            b1 = b1.add(b2);
        }
        return b1;
    }

    public static String tranTenThousandUnit(double v) {
        BigDecimal b = new BigDecimal(Double.toString(v));
        String s = b.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
        return s;
    }

    public static String tranTenThousandUnit(int v) {
        BigDecimal b = new BigDecimal(Double.toString(v));
        String s = b.divide(new BigDecimal(10000), 2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
        return s;
    }

    /**
     * 当月最后一天
     *
     * @return
     */
    public static int getLastDayOfTheMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        ////获得本月第一天
        //calendar.add(Calendar.MONTH, 0);
        //calendar.set(Calendar.DAY_OF_MONTH, 1);
        //String firstDay = sdf.format(calendar.getTime());
        //System.out.println("firstDay:"+ firstDay);
        //获得本月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = sdf.format(calendar.getTime());
        return Integer.parseInt(lastDay);
    }

    /**
     * 获取某时间段内所有年月
     *
     * @param startDate XXXX-XX
     * @param endDate XXXX-XX
     * @return
     * @throws ParseException
     */
    public static List<String> getYearMonthBetweenDate(String startDate, String endDate) throws ParseException {
        if (!(startDate.compareTo(endDate) <= 0)) {
            throw new RuntimeException("开始时间要<=结束时间");
        }
        List<String> yearMonths = Lists.newArrayList();
        Date d1 = new SimpleDateFormat("yyyy-MM").parse(startDate);//定义起始日期
        Date d2 = new SimpleDateFormat("yyyy-MM").parse(endDate);//定义结束日期  可以去当前月也可以手动写日期。
        Calendar dd = Calendar.getInstance();//定义日期实例
        dd.setTime(d1);//设置日期起始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        while (dd.getTime().before(d2)) {//判断是否到结束日期
            yearMonths.add(sdf.format(dd.getTime()));
            dd.add(Calendar.MONTH, 1);//进行当前日期月份加1
        }
        yearMonths.add(sdf.format(dd.getTime()));
        return yearMonths;
    }

}
